#
# fusion.core.signature
#
# Copyright 2007 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"""
Public-Key Signatures

See fusion.core.identity.
"""

from binascii import hexlify

from Crypto.Util.number import bytes_to_long, long_to_bytes
from fusion.lib.sexp import encode, decode

class Signature(object):
    def __init__(self, type, fp, data):
        self.type = type
        self.fp = fp            # digest of public key
        self.data = data        # tuple as defined by pycrypto

    def encode(self):
        data = map(long_to_bytes, self.data)
        return encode([self.type, self.fp] + data)

    @property
    def fingerprint(self):
        return hexlify(self.fp)

def decode_signature(string):
    parts = decode(string)
    if len(parts) < 3 or not all(isinstance(part, str) for part in parts):
        raise ValueError
    type, fp, data = parts[0], parts[1], parts[2:]
    data = tuple(map(bytes_to_long, data))
    sig = Signature(type, fp, data)
    if sig.encode() != string:
        raise ValueError        # Reject noncanonical encodings.
    return sig
